'use strict'

const hapi = require('@hapi/hapi')
const db = require('./src/sql/db')

const server = hapi.server({
  port: 3000,
  host: 'localhost',
})

server.route(
  {
    method: 'GET',
    path: '/userInfo',
    handler: async (request, h) => {
      try {
        const results = await new Promise((resolve, reject) => {
          db.query('SELECT * FROM userInfo', (error, results, fields) => {
            if (error) {
              console.error('查询失败:', error)
              reject(error)
            }
            resolve(results)
          })
        })

        return h
          .response({
            status: 'success',
            data: results,
          })
          .code(200)
      } catch (err) {
        console.error('服务器错误:', err)
        return h
          .response({
            status: 'error',
            message: '无法获取用户信息',
          })
          .code(500)
      }
    },
  },
  {}
)

const start = async () => {
  try {
    await server.start(() => {
      // ✅ 在这里执行启动后的逻辑
      console.log('Server running on %s', server.info.uri)
      // 测试数据库连接
      db.query('SELECT 1 AS test', (err, results) => {
        if (err) console.error('数据库连接失败:', err)
        else console.log('数据库连接成功:', results[0][0])
      })
    })
  } catch (err) {
    console.error('Server start error:', err)
    process.exit(1)
  }
}

start()
